package cn.ym.mall.service.impl;

import cn.ym.mall.dao.ContractDao;
import cn.ym.mall.dao.impl.ContractDaoImpl;
import cn.ym.mall.entity.Contract;
import cn.ym.mall.entity.Staff;
import cn.ym.mall.service.ContractService;
import cn.ym.mall.utils.DruidUtils;
import cn.ym.mall.vo.Page;

import java.sql.Connection;
import java.sql.SQLException;

public class ContractServiceImpl implements ContractService {
    ContractDao contractDao = new ContractDaoImpl();

    /**
     * 分页查询所有合同
     *
     * @param pageNo
     * @param pageSize
     * @return
     * @throws SQLException
     */
    @Override
    public Page<Contract> getAll(Integer pageNo, Integer pageSize) throws SQLException {
        Connection conn = null;
        Page<Contract> contractPage = new Page<>();
        try {
            conn = DruidUtils.getConnection();
            contractPage.setPageNo(pageNo);
            contractPage.setPageSize(pageSize);
            contractPage.setCount(Math.toIntExact(Long.valueOf(contractDao.getCount())));//long转int类型转换
            contractPage.setList(contractDao.getAll(pageNo,pageSize));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DruidUtils.close();
        }
        return contractPage;
    }

    /**
     * 添加新合同
     *
     * @param contract
     * @return
     * @throws SQLException
     */
    @Override
    public boolean add(Contract contract) throws SQLException {
        Connection conn = null;
        try {
            conn = DruidUtils.getConnection(false);
            if (contractDao.add(contract) == 1){
                DruidUtils.commit();
                return true;
            }else {
                DruidUtils.rollback();
            }
        }catch (Exception e){
            DruidUtils.rollback();
            e.printStackTrace();
        }finally {
            DruidUtils.close();
        }
        return false;
    }

    /**
     * 合同编号查询合同
     *
     * @param coid
     * @return
     * @throws SQLException
     */
    @Override
    public Contract getContractByCoid(Integer coid) throws SQLException {
        Connection conn = null;
        Contract contract = null;
        try {
            conn = DruidUtils.getConnection();
            contract = contractDao.getContractByCoid(coid);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DruidUtils.close();
        }
        return contract;
    }

    /**
     * 商店编号查询合同
     *
     * @param sid
     * @return
     * @throws SQLException
     */
    @Override
    public Contract getContractBySid(Integer sid) throws SQLException {
        Connection conn = null;
        Contract contract = null;
        try {
            conn = DruidUtils.getConnection();
            contract = contractDao.getContractBySid(sid);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DruidUtils.close();
        }
        return contract;
    }
}
